<template>
  <div class="carbonEmissions">
    <div style="padding-left: 20px;">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-button style="padding: 0" size="mini">
          <el-upload :limit="limitNumber" action="" accept=".xls, .xlsx" ref="uploadExcelRef"
                     :auto-upload="false" :show-file-list="false" :on-change="handleAddFun">
            <el-button size="mini" type="projectBut" icon="el-icon-upload2">上传数据</el-button>
          </el-upload>
        </el-button>


        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-row>

      <el-table v-loading="loading" :height="tableHeight" :data="emissionList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="名称" align="center" prop="iname" />
        <el-table-column label="排放日期" align="center" prop="creationTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.creationTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="消耗量(t)" align="center" prop="consumption" />
        <el-table-column label="排放因子(tCO₂/t)" align="center" prop="emissionFactor" />
        <el-table-column label="碳排放量(tCO₂)" prop="carbonEmissions" align="center"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="130">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改脱硝排放对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body custom-class="show-back-class">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="iname">
          <el-input v-model="form.iname" placeholder="请输入脱硝名称" />
        </el-form-item>
        <el-form-item label="排放日期" prop="creationTime">
          <el-date-picker clearable size="small" style="width: 200px" popper-class="show-back-class date-select-class"
                          v-model="form.creationTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择排放日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="消耗量" prop="consumption">
          <el-input v-model="form.consumption" placeholder="请输入消耗量" >
            <template slot="append">t</template>
          </el-input>
        </el-form-item>
        <el-form-item label="排放因子" prop="emissionFactor">
          <el-input v-model="form.emissionFactor" placeholder="请输入排放因子" >
            <template slot="append">tCO₂/t</template>
          </el-input>
        </el-form-item>
        <el-form-item label="资料文件上传">
        <el-upload class="upload-demo" :action="uploadBasecUrl" :headers="{'Authorization': Authorization }" :on-preview="handlePreview" :on-remove="handleRemove"
         :before-remove="beforeRemove" multiple :limit="5" :on-exceed="handleExceed" :on-success="upLoadSuccess" :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmission, getEmission, delEmission, addEmission, updateEmission, exportEmission,changeData } from "@/api/carbon/nitreEmission";
import {calNitreEmission} from "@/api/comput/comput";
import { getToken } from '@/utils/auth'
import * as XLSX from "xlsx";

export default {
  name: "Emission",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 脱硝排放表格数据
      emissionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        iname: null,
        creationTime: null,
        consumption: null,
        emissionFactor: null
      },
      // 表单参数
      form: {},
      limitNumber: 1,
      projectId: '',
      // 表单校验
      rules: {
      },
      tableHeight:'',
      uploadBasecUrl:'',
      Authorization:'',
      fileList: [],
    };
  },
  created() {
    this.uploadBasecUrl = process.env.VUE_APP_BASE_API  + '/common/upload'
    this.Authorization = 'Bearer ' + getToken();
    this.tableHeight = 560;
    this.projectId = this.$store.state.projectDict.projectId;
    this.getList();
  },
  methods: {
    /** 查询脱硝排放列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectId = this.projectId;
      listEmission(this.queryParams).then(response => {
        this.emissionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: this.projectId,
        iname: null,
        creationTime: null,
        consumption: null,
        emissionFactor: 0.73,
        accessoryUrl: null,
        accessoryName: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加脱硝排放";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEmission(id).then(response => {
        this.form = response.data;
        let fileListArr = [];
        let fileListName = [];
        this.fileList = [];
        if(row.accessoryUrl.length != 0 && row.accessoryName.length != 0) {
          fileListArr = row.accessoryUrl.split(',');
          fileListName = row.accessoryName.split(',');
          for(let i = 0; i < fileListArr.length; i++) {
            this.fileList.push({name:fileListName[i],url:fileListArr[i]})
          }
        }
        this.form.projectId = this.projectId;
        this.open = true;
        this.title = "修改脱硝排放";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        let fileListArr = [];
        let fileListName = [];
        this.fileList.map(item => {
          fileListArr.push(item.url);
          fileListName.push(item.name);
        })
        if (valid) {
          this.form.accessoryUrl = fileListArr.join(',');
          this.form.accessoryName = fileListName.join(',');
          if (this.form.id != null) {
            updateEmission(this.form).then(response => {
              if (response.code === '200') {
                this.msgSuccess("修改成功");
                this.fileList = [];
                this.open = false;
                // this.getList();
                this.calCarbon();
              }
            });
          } else {
            this.form.accessoryUrl = fileListArr.join(',');
            this.form.accessoryName = fileListName.join(',');
            addEmission(this.form).then(response => {
              if (response.code === '200') {
                this.msgSuccess("新增成功");
                this.fileList = [];
                this.open = false;
                // this.getList();
                this.calCarbon();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除脱硝排放编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delEmission(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },


    /** 选择文件上传 */
    async handleAddFun(file) {
      let that = this
      let tableList = [];
      that.regionList = [];
      that.hourData = [];
      const excel = await this.readFile(file.raw)
      let wb = XLSX.read(excel, { type: 'binary' })
      let object = {};//默认的序列
      let params = JSON.parse(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])));//基本信息
      console.log(params);
      // Object.assign(object,params,other);
      Object.assign(object,params);
      that.limitNumber ++;
      that.regionList.push(object);
      tableList = tableList.concat(that.fixData(that.regionList));
      //  that.emissionList = that.emissionList.concat(that.fixData(that.regionList));
      that.showList(tableList,1);
      changeData({
        nitreEmissionList: tableList,
        projectId: that.projectId
      }).then(res => {
        if(res.code == 200) {
          this.msgSuccess("上传成功");
          that.calCarbon();
        }
      })
    },
    showList(dataList,n){
      let that =this;
      if(n*200>dataList.length){
        return
      }
      that.timeoutId =  setTimeout(function () {
        let a;
        if((n+1)*200>dataList.length){
          a = dataList.slice(n*200)
        }else {
          a = dataList.slice(n*200,(n+1)*200)
        }
        that.hourData = that.hourData.concat(a)
        n++
        that.showList(dataList,n)
      }, 1000);
    },
    // 整理表格数据
    fixData(data) {
      let tableList = [];
      let dataArr = [];
      const firstData = Array.isArray(data[0]) ? data[0] : [data[0]];
      Object.keys(firstData[0]).forEach(key => {
        if (!isNaN(key)) {  // Check if the key is a number
          dataArr.push(firstData[0][key]);
        }
      });
      for (let i = 0;i<dataArr.length;i++) {
        tableList.push({
          iname: dataArr[i]['名称'] == null ||  dataArr[i]['名称'] == undefined?dataArr[i]['名称'] = '':dataArr[i]['名称'] = dataArr[i]['名称'],
          creationTime: dataArr[i]['排放日期'] == null ||  dataArr[i]['排放日期'] == undefined?dataArr[i]['排放日期'] = '':dataArr[i]['排放日期'] = dataArr[i]['排放日期'],
          consumption: dataArr[i]['消耗量'] == null ||  dataArr[i]['消耗量'] == undefined?dataArr[i]['消耗量'] = 0:dataArr[i]['消耗量'] = dataArr[i]['消耗量'],
          emissionFactor: dataArr[i]['排放因子'] == null ||  dataArr[i]['排放因子'] == undefined?dataArr[i]['排放因子'] = 0:dataArr[i]['排放因子'] = dataArr[i]['排放因子'],
          accessoryUrl: dataArr[i]['资料文件'] == null ||  dataArr[i]['资料文件'] == undefined?dataArr[i]['资料文件'] = '':dataArr[i]['资料文件'] = dataArr[i]['资料文件'],
        })
      }
      return tableList;
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有脱硝排放数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportEmission(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    },
    calCarbon() {
      calNitreEmission({projectId: this.projectId}).then(res => {
        if(res.code == 200) {
          this.$message.success('计算成功');
          this.getList();
        } else {
          this.$message.error("计算失败");
        }
      });
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.name !== file.name);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    upLoadSuccess(response,file) {
      this.fileList.push({name:file.name,url:response.fileName});
    }
  }
};
</script>
<style scoped lang="scss">
  .carbonEmissions {
    width: 100%;
    height: 100%;
  }
</style>
